package com.ciwong.epaper.modules.epaper.ui.newlistenspeak;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.LsRedoAnswersEvent;
import com.ciwong.epaper.modules.dbbean.AnswerContent;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.ListenspeakExam;
import com.ciwong.epaper.modules.epaper.bean.ModuleSet;
import com.ciwong.epaper.modules.epaper.bean.QuestionRule;
import com.ciwong.epaper.modules.epaper.bean.QuestionScore;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.ResourceDetail;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.ui.SelectQuestionDialog;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.epaper.util.LswSelectTipDialog;
import com.ciwong.epaper.modules.epaper.util.LswTipDialog;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.viedoexplantion.util.ViedoJumpManager;
import com.ciwong.epaper.ui.MainActivity;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.audio.recorder.Mp3Recorder;
import com.ciwong.libs.audio.recorder.OnRecorderListener;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DateFormat;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.BaseRequestUtil;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;

/**
 * Created by Administrator on 2017/2/10.
 */
public class NewListenSpeakActivity extends NewBaseListenSpeakActivity {

    /**
     * 大题播放次数，大题看题时间、大题准备时间。
     * 小题播放次数，小题看题时间，小题准备时间，小题答题时间
     **/
    public static final String TAG = "newlistenspeak";

    protected final int MSG_DISMISS_NET_TIPS = 107;

    private static final long PLAY_WAIT_TIME = 3000;// 多次播放间隔时间  // 播放附件音频
    //资源内容及播放要求
    private String mRecorderPath;// 录音路径
    public static final String UPLOAD_TAG = "uploadTag";
    // 去选题界面
    private static final int REQ_CODE_TO_SELECT_QUESTION = 1;
    //是否是自主练习切换大题
    private boolean isBigQuesSwitch = false;
    //    private NetWorkTipsDialog mNetWorkTipsDialog;
    private Timer timer = new Timer();

    private int mRecordSoundDb;

    @Override
    public void init() {
        super.init();
        AudioPlayer.getInstance().setOnPlayListener(playListener);
    }

    @Override
    protected void loadData() {
        try {
            //获取保存的作业记录ID  获取保存的uuid  提交完成会删除当前SAVEUUid  做作业UUID
            final String saveUUid = CWSys.getSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), null);
            final long startTime = CWSys.getSharedLong(ListenSpeakUtil.getStartDateSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), System.currentTimeMillis());
            isReadBigQuestionStem = CWSys.getSharedBoolean(EConstants.SHARE_KEY_IS_PLAY_STEM_AUDIO + getUserInfoBase().getUserId(), true);
            if (EConstants.IS_YOUKE && EConstants.LISTENSPEAK_IS_YOUKE_LOGIN) {
                //重新开始的学习
                restartLoadData();
                EConstants.LISTENSPEAK_IS_YOUKE_LOGIN = false;
                //新一次缓存，提交完成后清除本次活动key
                CWSys.setSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), uuid);
                CWSys.setSharedLong(ListenSpeakUtil.getStartDateSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), startDate);
            } else {
                EConstants.LISTENSPEAK_IS_YOUKE_LOGIN = false;
                if (TextUtils.isEmpty(saveUUid) || saveUUid == null) {
                    //新开始的学习
                    restartLoadData();
                    //新一次缓存，提交完成后清除本次活动key
                    CWSys.setSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), uuid);
                    CWSys.setSharedLong(ListenSpeakUtil.getStartDateSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), startDate);
                } else {
                    //继续上次学习
                    //继续使用上次的UUID
                    uuid = saveUUid;
                    startDate = startTime;
                    getUploadStateRecordList();
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        isStopHandler = false;
        if (isRecordFail) {
            isRecordFail = false;
            restartBigQuestion(mBigQuesIndex);
        }
        question_layout.enableBlankInput();
    }

    /**
     * 获取保存的作答音频上传记录
     * 作答音频的上传状态   及用户答案列表
     */
    protected void getUploadStateRecordList() {
        SerializableManager.getInstance().deSerialize(ListenSpeakUtil.getSaveLsAnswerListKey(mDownLoadInfo, mModule, position, intentWorkId, uuid),

                new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        mLswAnswerList = (ArrayList<LswAnswer>) data;

                        workTime = (int) (System.currentTimeMillis() - startDate) / 1000;
                        int saveWorkTime = CWSys.getSharedInt(ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);
                        if (workTime < saveWorkTime || workTime < 0) {
                            workTime = saveWorkTime;
                        }
                        //从上次保存的记录开始做题
                        final int questionNo = CWSys.getSharedInt(ListenSpeakUtil.getSaveQuesNoKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);
                        final int questionTotalNo = CWSys.getSharedInt(ListenSpeakUtil.getSaveTotalIndexKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);
                        final int questionSmallNo = CWSys.getSharedInt(ListenSpeakUtil.getSaveSmallQuesKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);
                        final int questionStatus = CWSys.getSharedInt(ListenSpeakUtil.getSaveStatusQuesKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);

                        // 题目总数
                        int questionCount = CWSys.getSharedInt(ListenSpeakUtil.getSaveQuesCountKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);
                        //            final boolean isOver = questionCount >= 0
                        //                    && questionNo + 1 >= questionCount;// 是否完成了学习
                        //解决做到倒数第二题的时候提示做完，不用加1 了，因为缓存题目时已经是加1再缓存了
                        boolean isOver = questionCount >= 0 && questionNo >= questionCount;// 是否完成了学习
                        //完成了本次学习


                        //这种情况是用户自主练习没做完点击完成到提交作业页面，下次进来也要到提交作业页面
                        if (!isOver && (lsMode == ListenSpeakUtil.LsMode.OWN_PRACTISE || lsMode == ListenSpeakUtil.LsMode.HOME_WORK_MODE)) {
                            isOver = CWSys.getSharedBoolean(ListenSpeakUtil.getBeenToRedoPageRecord(mDownLoadInfo, mModule, position, intentWorkId, uuid), false);
                        }


                        if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {

                            mBigQuesIndex = mRetryIndex;
                            getExamData(false);

                        } else if (isOver) {
                            //跳转到结果页面
                            boolean beenToResult = CWSys.getSharedBoolean(ListenSpeakUtil.getBeenToLswResultRecord(mDownLoadInfo, mModule, position, intentWorkId, uuid), false);
                            if (beenToResult) {
                                //之前到过结果页面直接到结果页面，没有就到交作业页面
                                EpaperJumpManager.jumpToListenSpeakResult(R.string.listen_speak,
                                        mActivity, isCorrect, mDownLoadInfo, mModule, checkedResource, position, intentWorkId, mClassId, workTime, mServiceId, mLswAnswerList, mExamData,
                                        RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, mWorkContents, lsMode, doWorkType, effectivDate);
                                finish();
                            } else {
                                userAnswerOver();
                            }

                        } else {
                            //继续做题
                            isShowTips = true;
                            Log.e(TAG, "success: " + isShowTips);

                            mBigQuesIndex = questionNo;
//                            mSmallQuesIndex = questionSmallNo;
//                            status = ListenSpeakUtil.getStateByIndex(questionStatus);
                            if (0 == questionNo) {
                                mQuesTotalIndex = 0;
                            } else {
                                mQuesTotalIndex = questionTotalNo;
                            }
                            if (isCorrect) {
                                mBigQuesIndex = 0;
                                mQuesTotalIndex = 0;
                            }

                            getExamData(false);

                        }
                    }


                    @Override
                    public void failed(int errorCode, Object data) {
                        failed(null);
                    }

                    @Override
                    public void failed(Object data) {

                        workTime = (int) (System.currentTimeMillis() - startDate) / 1000;
                        int saveWorkTime = CWSys.getSharedInt(ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);
                        if (workTime < saveWorkTime || workTime < 0) {
                            workTime = saveWorkTime;
                        }
                        //这种情况是用户自主练习没做完点击完成到提交作业页面，下次进来也要到提交作业页面
                        boolean isOver = false;
                        if (lsMode == ListenSpeakUtil.LsMode.OWN_PRACTISE) {
                            isOver = CWSys.getSharedBoolean(ListenSpeakUtil.getBeenToRedoPageRecord(mDownLoadInfo, mModule, position, intentWorkId, uuid), false);
                        }

                        if (isOver) {

                            boolean beenToResult = CWSys.getSharedBoolean(ListenSpeakUtil.getBeenToLswResultRecord(mDownLoadInfo, mModule, position, intentWorkId, uuid), false);
                            if (beenToResult) {
                                //之前到过结果页面直接到结果页面，没有就到交作业页面
                                EpaperJumpManager.jumpToListenSpeakResult(R.string.listen_speak,
                                        mActivity, isCorrect, mDownLoadInfo, mModule, checkedResource, position, intentWorkId, mClassId, workTime, mServiceId, mLswAnswerList, mExamData,
                                        RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, mWorkContents, lsMode, doWorkType, effectivDate);
                                finish();
                            } else {
                                userAnswerOver();
                            }
                            return;
                        }

                        //获取失败   重新做题
                        if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {
                            mBigQuesIndex = mRetryIndex;
                        } else {
                            mBigQuesIndex = 0;
                        }

                        //mCacheAnswerIndex=mBigQuesIndex;
                        String saveUuid = CWSys.getSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType));
                        FileUtils.delete(ESystem.getAnswersUuidPath(saveUuid));
                        clearRecord();
                        getExamData(false);
                    }
                });
    }

    private void showRecordTips() {
        if (lsMode != ListenSpeakUtil.LsMode.RETRY_MODE && isShowTips) {
            Animation animation = AnimationUtils.loadAnimation(NewListenSpeakActivity.this, R.anim.slide_down2);
            tx_record_continue_tips.startAnimation(animation);
            tx_record_continue_tips.setVisibility(View.VISIBLE);
            mRecorderHandler.sendEmptyMessageDelayed(MSG_DISMISS_NET_TIPS, 3000);
            isShowTips = false;
        }

    }


    private void restartLoadData() {
        //第一次做   或者出错情况下 重新开始
        mBigQuesIndex = 0;
        clearRecord();
        getExamData();
    }


    Handler mRecorderHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {


            try {

                if (isFinishing()) {
                    return true;
                }

                if (isStopHandler) {
                    isStopHandler = false;
                    return true;
                }

                if (isStopFlag) {
                    isStopFlag = false;
                    return true;
                }

                CWLog.d(TAG, "########录音msg.what#########" + msg.what);

                switch (msg.what) {//mp3Record  start 后，由jar 包里发出Mp3Recorder.MSG_REC_STARTED 消息
                    case Mp3Recorder.MSG_REC_STARTED:// 录音开始
                        ls_bottom_view.microRecordingSetVisibility(View.VISIBLE);

                        CWLog.d(TAG, "########录音倒计时#########");
                        //录音倒计时
                        startRecordTimeCount();
                        mRecordSoundDb = 0;
                        break;
                    case Mp3Recorder.MSG_DB:// 录音分贝
                        Bundle b = msg.getData();
                        if (b != null) {
                            double db = b.getDouble("db");
                            //                        CWLog.d(TAG, "########录音音量#########"+db);

                            if (!Double.isNaN(db)) {
                                ls_bottom_view.microRecordingSetRms(db);
                                int soundDb = Double.valueOf(db).intValue();

                                if (soundDb > mRecordSoundDb) {
                                    mRecordSoundDb = soundDb;
                                }

                                //                            microRecording.setRms(db);
                            } else {
                                CWLog.d(TAG, "########Double.isNaN(db)#########" + db);
                            }
                        }
                        break;
                    case Mp3Recorder.MSG_ERROR_AUDIO_RECORD:// 录音失败
                        CWLog.d(TAG, "########     Mp3Recorder.MSG_ERROR_AUDIO_RECORD    录音失败#########");
                        //出现录音失败就不应该继续做题
                        isRecordFail = true;
                        DialogUtil.showSettingPermissions(NewListenSpeakActivity.this);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_AUDIO_RECORD", "录音失败回调");
                        break;
                    case Mp3Recorder.MSG_ERROR_REC_START:
                        CWLog.d(TAG, "########     Mp3Recorder.MSG_ERROR_AUDIO_RECORD    录音失败#########");
                        //出现录音失败就不应该继续做题
                        isRecordFail = true;
                        DialogUtil.showSettingPermissions(NewListenSpeakActivity.this);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_REC_START", "录音失败回调");
                        break;
                    case Mp3Recorder.MSG_ERROR_AUDIO_ENCODE:
                        ToastUtil.INSTANCE.toastCenter(NewListenSpeakActivity.this, "录音处理编码失败，请重新作答！", R.mipmap.ic_increase_volume);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_AUDIO_ENCODE", "录音处理编码失败回调");
                        break;
                    case Mp3Recorder.MSG_ERROR_WRITE_FILE:
                        ToastUtil.INSTANCE.toastCenter(NewListenSpeakActivity.this, "录音读取文件失败，请重新作答！", R.mipmap.ic_increase_volume);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_WRITE_FILE", "录音读取文件失败回调");
                        break;
                    case Mp3Recorder.MSG_ERROR_CLOSE_FILE:
                        ToastUtil.INSTANCE.toastCenter(NewListenSpeakActivity.this, "录音关闭读取失败，请重新作答！", R.mipmap.ic_increase_volume);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_CLOSE_FILE", "录音关闭读取失败回调");
                        break;
                    case Mp3Recorder.MSG_REC_STOPPED:// 录音结束
                        try {
                            if (isRecordFail) {
                                ToastUtil.INSTANCE.toastCenter(NewListenSpeakActivity.this, "录音结束失败，请重新作答！", R.mipmap.ic_increase_volume);
                                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_REC_STOPPED", "录音结束失败回调isRecordFail：" + isRecordFail);
                                break;
                            }
                            if (mRecordSoundDb < 55) {
                                ToastUtil.INSTANCE.toastCenter(NewListenSpeakActivity.this, R.string.read_sound_too_low_tips, R.mipmap.ic_increase_volume);
                            }


                            status = ListenSpeakUtil.State.END_AUDIO;
                            /*bigQuesIndex = mBigQuesIndex+1;
                            totalQuesIndex = mQuesTotalIndex+1;
                             if (mChildQuesIndex == -1){
                                quesNo = (mBigQuesIndex+1)+"."+(mSmallQuesIndex+1);
                            }else {
                                quesNo = (mBigQuesIndex+1)+"."+(mSmallQuesIndex+1)+"."+(mChildQuesIndex+1);
                            }*/
                            if (!mAheadRecord) {
                                AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_END_AUDIO, NewListenSpeakActivity.this, null);
                            } else {
                                List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
                                List<Questions> childQuesList = null;
                                // 有小题
                                if (smallQuesList != null && !smallQuesList.isEmpty() && mSmallQuesIndex < smallQuesList.size()) {
                                    childQuesList = smallQuesList.get(mSmallQuesIndex).getChildren();
                                }
                                if (smallQuesList != null && mSmallQuesIndex >= smallQuesList.size() - 1 &&
                                        childQuesList != null && !childQuesList.isEmpty() && mChildQuesIndex >= childQuesList.size() - 1) {
                                    if (mResourceList.get(mBigQuesIndex).getQuestions().get(0).getEndAudioUrl() != null && !mResourceList.get(mBigQuesIndex).getQuestions().get(0).getEndAudioUrl().equals("")) {
                                        status = ListenSpeakUtil.State.END_LATS_AUDIO;
                                        AudioPlayer.getInstance().play(ESystem.formatPath(mResourceList.get(mBigQuesIndex).getQuestions().get(0).getEndAudioUrl()));
                                        ls_bottom_view.showPlayButton(mQuestionType);
                                        break;
                                    }
                                }
                                //playLastAudio();
                                mAheadRecord = false;
                                if (mBigQuesIndex < mResourceList.size()) {
                                    int infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
                                    accomplishRecord(infoRetail);
                                }
                            }
                        } catch (Exception e) {
                            ToastUtil.INSTANCE.toastCenter(NewListenSpeakActivity.this, "录音结束失败Exception，请重新作答！", R.mipmap.ic_increase_volume);
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音回调：Mp3Recorder.MSG_REC_STOPPED：" + e.getMessage(), "录音结束失败Exception");
                            e.getStackTrace();
                        }
                        break;
                    case ListenSpeakUtil.HandlerWhat.PLAY_SOUND:// 播放声音
                        isShowTime = true;
                        if (msg.obj != null && !TextUtils.isEmpty(msg.obj.toString())) {
                            ls_bottom_view.showPlayButton(mQuestionType);
                            AudioPlayer.getInstance().play(msg.obj.toString());
                            try {
                                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                                    MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                                    if (mMediaPlayer != null) {
                                        try {
                                            PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                            if (params != null) {
                                                mMediaPlayer.setPlaybackParams(params);
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    case MSG_DISMISS_NET_TIPS:
                        Animation animation2 = AnimationUtils.loadAnimation(NewListenSpeakActivity.this, R.anim.slide_up2);
                        animation2.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {
                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                tx_record_continue_tips.setVisibility(View.GONE);
                                //                            getExamData(false);
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                        tx_record_continue_tips.startAnimation(animation2);

                        break;
                    default:
                        ToastUtil.INSTANCE.toastCenter(NewListenSpeakActivity.this, "录音失败,未知问题，请重新作答！", R.mipmap.ic_increase_volume);
                        break;
                }

            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            return true;
        }
    });

    @Override
    protected void onPlayBigStem() {
        onBigStemPlayOver();
    }


    //播放器监听
    private OnPlayListener playListener = new OnPlayListener() {
        @Override
        public void stop(Object audioUrl) {
            //1 信息转述 2 自主提问 3 视频朗读
            int infoRetail = -1;
            try {
                if (isFinishing()) {
                    return;
                }
                //设置播放按钮状态
                ls_bottom_view.setPlayBtnState(false);
                if (isStopFlag) {
                    isStopFlag = false;
                    return;
                }

                if (mBigQuesIndex < mResourceList.size()) {
                    infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
                }


                CWLog.d(TAG, "播放结束，status=" + status + "----infoRetail" + infoRetail);

                ls_bottom_view.setNextTipsVisibility(View.INVISIBLE);
            } catch (Exception e) {
                e.getStackTrace();
            }

            switch (status) {
                case START:// 开始答题

                    //总计时开始
                    startTotalCount();
                    if (mBigQuesIndex < mResourceList.size()) {
                        //young  new question of long  or short

                        //开始播放大题音频
                        startLoadBigQuestion(mResourceList);

                    }


                    break;
                case BIG_QUESTION_STEM:// 单个大题题干音频播放完毕（重复播放同一音频）
                    CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_PLAY + getUserInfoBase().getUserId(), true);


                    //                    if (mSwitchBigQuestion) {
                    //                        mSwitchBigQuestion=false;
                    //                        return;
                    //                    }
                    onBigStemPlayOver();

                    break;
                case SMALL_QUESTION_STEM:// 单个小题题干播放完毕(连续播放附件内的音频)
                case CHILD_QUESTION_STEM:// 单个子题题干播放完毕(连续播放附件内的音频)

                    try {
                        ls_bottom_view.hideTimerAnimation();
                        // 播放计数
                        playCount--;
                        if (playCount > 0) {
                            isPlayAgain = true;
                            isShowTime = false;// 间隔时间内不需要显示倒计时
                            Message msg = new Message();
                            // 播放音频
                            msg.what = ListenSpeakUtil.HandlerWhat.PLAY_SOUND;
                            msg.obj = audioUrl;
                            mRecorderHandler.sendMessageDelayed(msg, PLAY_WAIT_TIME);// 播放附件音频  // 多次播放间隔时间3000  // 播放附件音频

                        } else {
                            isPlayAgain = false;
                            playCount = progress = 0;
                            removeHandlerMsg(ListenSpeakUtil.HandlerWhat.PLAY_SOUND, mRecorderHandler);
                            // 播放小题音频
                            attachmentExceptionOrStoped();
                        }
                    } catch (Exception e) {
                        e.getStackTrace();
                    }
                    break;
                case ANSWER:// 开始答题/录音音频播放完毕
                    try {
                        Log.d(TAG, "#########允许开始答题########");
                        if (mBigQuesIndex < mResourceList.size()) {
                            timeCount = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule().getAnswerTime();// 取得答题时间
                            ls_bottom_view.seekBarSetMax(timeCount);
                        }

                        //                    seekbarTimer.setMax(mTimeCount);
                        // setOptionsEnable(true);// 可以答题
                        int infoRetail2 = -1;
                        List<String> urlList2 = null;

                        if (mBigQuesIndex < mResourceList.size()) {
                            infoRetail2 = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
                            //视频朗读
                            if (infoRetail2 == 3 && null != mResourceList.get(mBigQuesIndex).getQuestions() && mSmallQuesIndex < mResourceList.get(mBigQuesIndex).getQuestions().size()
                                    && mResourceList.get(mBigQuesIndex).getQuestions().get(mSmallQuesIndex).getChildren() != null && mChildQuesIndex < mResourceList.get(mBigQuesIndex).getQuestions().get(mSmallQuesIndex).getChildren().size()) {
                                Questions questions2 = mResourceList.get(mBigQuesIndex).getQuestions().get(mSmallQuesIndex).getChildren().get(mChildQuesIndex);
                                urlList2 = ListenSpeakUtil.getVideoPath(questions2.getTrunk());
                            }
                        }

                        //题目类型:选择题
                        if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE || mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {


                            if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {

                                Log.d("RemoveAllViews", "########ls_bottom_view.setStateBarVisibility(View.GONE)#########");

                                ls_bottom_view.setStateBarVisibility(View.GONE);

                                question_layout.showSoftInput(true);
                            }
                            startRecordTimeCount();
                            //视频朗读

                        } else if (infoRetail2 == 3 && null != urlList2 && urlList2.size() > 0) {   //是否是录音评测


                            //得到音频保存地址
                            mRecorderPath = ESystem.getAnswersMediaPath(uuid) + File.separator + System.currentTimeMillis() + EConstants.AUDIO_DEFAULT_SUFFIX;
                            ViedoJumpManager.jumpToListenSpeakVideo(R.string.go_back, NewListenSpeakActivity.this, EpaperConstant.REQUEST_CODE_LISTEN_SPEAK_VIDEO_AND_RECORD, urlList2.get(0), EpaperConstant.LISTEN_SPEAK_PLAY_TYPE_NEED_RECORD, mRecorderPath, mResourceName, question_layout.getBigStem());

                        } else {
                            CWLog.d(TAG, "题目类型：" + mQuestionType);
                            progress = 0;
                            startRecorder();
                        }
                    } catch (Exception e) {
                        e.getStackTrace();
                    }


                    break;
                case END_AUDIO:// 录音结束音频播放完毕
                    try {

                        //  playLastAudio();
                        //当前层级是否有子题，子题遍历，是否有小题，小题是否遍历完，大题遍历
                        if (isFinishing()) {
                            return;
                        }
                        List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
                        List<Questions> childQuesList = null;

                        // 有小题
                        if (smallQuesList != null && !smallQuesList.isEmpty() && mSmallQuesIndex < smallQuesList.size()) {
                            childQuesList = smallQuesList.get(mSmallQuesIndex).getChildren();
                        }
                        if (smallQuesList != null && mSmallQuesIndex >= smallQuesList.size() - 1 &&
                                childQuesList != null && !childQuesList.isEmpty() && mChildQuesIndex >= childQuesList.size() - 1) {
                            if (mResourceList.get(mBigQuesIndex).getQuestions().get(0).getEndAudioUrl() != null && !mResourceList.get(mBigQuesIndex).getQuestions().get(0).getEndAudioUrl().equals("")) {
                                status = ListenSpeakUtil.State.END_LATS_AUDIO;
                                AudioPlayer.getInstance().play(ESystem.formatPath(mResourceList.get(mBigQuesIndex).getQuestions().get(0).getEndAudioUrl()));
                                try {
                                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                                        MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                                        if (mMediaPlayer != null) {
                                            try {
                                                PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                                if (params != null) {
                                                    mMediaPlayer.setPlaybackParams(params);
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                ls_bottom_view.showPlayButton(mQuestionType);
                                break;
                            }
                        }


                        if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE
                                || mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
                            autoSwitchNextQuestion(mResourceList);

                        } else {
                            accomplishRecord(infoRetail);
                        }
                    } catch (Exception e) {
                        e.getStackTrace();
                    }


                    break;
                case END_LATS_AUDIO:// 阅读理解标准题型  最后一题
                    try {
                        if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE
                                || mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
                            autoSwitchNextQuestion(mResourceList);

                        } else {
                            accomplishRecord(infoRetail);
                        }
                    } catch (Exception e) {
                        e.getStackTrace();
                    }


                    break;
                case END:// 结束
                    CWLog.d(TAG, "END-提交答案");
                    //缓存大题索引，答案
                    //因为mBigQuesIndex 最后一道大题没有加1，比总数少一
                    mBigQuesIndex = mExamData.getItems().size();
                    serializeRecord(mBigQuesIndex, workTime, mQuesTotalIndex, mSmallQuesIndex, status);
                    toSubmitAnswer();
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPlaying(long duration, long mProgress) {
            if (isFinishing()) {
                return;
            }

            int remainCount;
            Spannable span;
            switch (status) {
                case BIG_QUESTION_STEM:
                    // 更新时间
                    remainCount = (int) (duration - mProgress) / 1000;
                    //                    Log.e(TAG, "onPlaying duration: "+duration +"  mProgress=  "+mProgress+"  remainCount=="+remainCount);
                    span = new SpannableString(getString(R.string.tip_timer2, getString(isPlayAgain ? R.string.tip_play_again : R.string.tip_play), remainCount + ""));
                    span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_light_green)), span.toString().indexOf("余") + 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    ls_bottom_view.updateTimer(span, progress, showSkipBtn, LsBottomView.SKIP_TYPE_PLAY_STEM, status, false);

                    if (question_layout.getOptionsLayout().getVisibility() == View.VISIBLE) {
                        //主干播放没完成选择填空题切题导致后面还会显示选项
                        Log.d("RemoveAllViews", "#####question_layout.optionsLayoutRemoveAllViews()############");
                        question_layout.optionsLayoutRemoveAllViews();
                    }

                    break;
                case SMALL_QUESTION_STEM:
                case CHILD_QUESTION_STEM:
                    progress = (int) mProgress;
                    ls_bottom_view.seekBarSetMax((int) duration);
                    if (isShowTime) {
                        // 更新时间
                        remainCount = (int) (duration - mProgress) / 1000;
                        span = new SpannableString(getString(R.string.tip_timer2, getString(isPlayAgain ? R.string.tip_play_again : R.string.tip_play), remainCount + ""));
                        span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_light_green)), span.toString().indexOf("余") + 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        if (mWorkContents != null && mWorkContents.getExamMode() != 0 && doWorkType != 1) {
                            ls_bottom_view.updateTimer(span, progress, false, LsBottomView.SKIP_TYPE_NULL, status, false);
                        } else {
                            ls_bottom_view.updateTimer(span, progress, true, LsBottomView.SKIP_TYPE_NULL, status, false);
                        }


                    }
                    break;

                default:
                    break;
            }
        }

        @Override
        public void onBuffer(Object arg0, long arg1, long arg2) {

        }

        @Override
        public void onError(int arg0, Object arg1) {
            if (isFinishing()) {
                return;
            }
            ToastUtil.INSTANCE.toastCenterError(R.string.play_audio_fail);
            CWLog.d(TAG, "playListener onError errcode:" + arg0 + ",object:" + arg1);
            //            removeHandlerMsg(ListenSpeakUtil.HandlerWhat.AUDIO_PLAY_ERROR, mHandler);
            //            mHandler.sendEmptyMessage(ListenSpeakUtil.HandlerWhat.AUDIO_PLAY_ERROR);
            playListener.stop(arg1);
        }

        @Override
        public void onPlayStart(Object arg0) {

        }

        @Override
        public void onReadPlayer(long arg0, Object arg1) {

        }
    };

    private void accomplishRecord(int infoRetail) {
        try {
            ls_bottom_view.hideTimerAnimation();
            //新需求服务器打分，录音结束启动打分api 请求
            startMakeScoreRequestAndSaveAnswer(getCurrentLswAnswer());
            if (mBigQuesIndex < mResourceList.size()) {
                infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();

                if (infoRetail == 2) {
                    //自主提问录完在播放音频资源
                    List<Questions> smallQuesList1 = mResourceList.get(mBigQuesIndex).getQuestions();
                    Questions smallQuestion = smallQuesList1.get(mSmallQuesIndex);
                    List<Questions> childQuesList = smallQuestion.getChildren();
                    startLoadChildQuestion(childQuesList.get(mChildQuesIndex), true, mResourceList);

                } else {///录音结束播放完成
                    autoSwitchNextQuestion(mResourceList);

                }
            }


        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    @Override
    protected void onTimeOver(ListenSpeakUtil.State timeOverType) {

        try {
            //准备时间结束
            progress = timeCount = 0;

            //允许选择题开始答题
            question_layout.allowAnswer(true);
            if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
                question_layout.showSoftInput(false);
            }
            ls_bottom_view.hideTimerAnimation();
            //        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
            if (mBigQuesIndex >= mResourceList.size()) {
                return;
            }
            List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
            // 当前状态   这个是状态值 //.UPDATE_TIME:// 更新时间 加上更新时间这个操作  才会走

            ls_bottom_view.setNextTipsVisibility(View.INVISIBLE);

            switch (timeOverType) {
                case LOOK_SMALL_QUESTION:// 小题阅题结束
                    //当阅题时间或者准备时间为0时，下一次还要展示引导提示语
                    if (mReadTime > 0 && mWorkContents != null && mWorkContents.getExamMode() == 0) {
                        CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_READ + getUserInfoBase().getUserId(), true);
                    }

                    if (smallQuesList != null && !smallQuesList.isEmpty()) {

                        Questions smallQuestion = smallQuesList.get(mSmallQuesIndex);
                        if (mBigQuesIndex >= mResourceList.size()) {
                            return;
                        }
                        int infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
                        Questions questions = mResourceList.get(mBigQuesIndex).getQuestions().get(mSmallQuesIndex);
                        CWLog.d(TAG, "------小题阅读结束-------infoRetail-------" + infoRetail);
                        List<String> urlList = ListenSpeakUtil.getVideoPath(questions.getTrunk());
                        //自主提问阅题结束后进入播放视频
                        if (infoRetail == 2 && null != urlList && urlList.size() > 0) {
                            //自主提问
                            ViedoJumpManager.jumpToListenSpeakVideo(R.string.go_back, NewListenSpeakActivity.this, EpaperConstant.REQUEST_CODE_LISTEN_SPEAK_INDEPENDENT_QUESTION, urlList.get(0), EpaperConstant.LISTEN_SPEAK_PLAY_TYPE_NO_NEED_RECORD, null, mResourceName, question_layout.getBigStem());

                        } else {
                            startLoadSmallQuestion(mResourceList, smallQuestion, true);
                        }

                    } else {
                        CWLog.i(TAG, "没有小题自动切换到下一题");
                        autoSwitchNextQuestion(mResourceList);
                    }
                    break;
                case READY_SMALL_QUESTION:// 小题准备倒计时结束
                    Log.d("bottomview", "############小题准备倒计时结束 ############mReadyTime##" + mReadyTime);

                    if (mReadyTime > 0) {
                        CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_PREPARE + getUserInfoBase().getUserId(), true);
                    }

                    if (smallQuesList != null && !smallQuesList.isEmpty()) {

                        Questions smallQues = smallQuesList.get(mSmallQuesIndex);
                        List<Questions> childQuesList = smallQues.getChildren();

                        if (childQuesList != null && !childQuesList.isEmpty()) {
                            //加载子题
                            mChildQuesIndex = 0;
                            Questions childQues = childQuesList.get(mChildQuesIndex);
                            if (mBigQuesIndex >= mResourceList.size()) {
                                return;
                            }

                            boolean isInfoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule().getInfoRetail() != 0;

                            if (isInfoRetail) {
                                QuestionRule listeningAndSpeakingRule = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule();
                                int audioViews = listeningAndSpeakingRule.getAudioViews();// 音频播放次数
                                int lookTime = listeningAndSpeakingRule.getLookTime();
                                int readyTime = listeningAndSpeakingRule.getReadyTime();
                                status = ListenSpeakUtil.State.CHILD_QUESTION_STEM;
                                startLoadAttachments(childQues.getTrunk(), audioViews, lookTime, readyTime, true, false);

                            } else {
                                /* switchChildQuestion(childQues,true);*///我在这里做了修改
                                switchChildQuestion(childQues, mResourceList);//在子题切换的时候第一次子题的应该为FALSE 这样才有看题时间 与后面的字题保持一致
                            }
                        } else {
                            startAnswerQuestion();
                        }
                    } else {
                        autoSwitchNextQuestion(mResourceList);
                    }
                    break;
                case LOOK_CHILD_QUESTION:// 子题阅题结束


                    if (mReadTime > 0 && mWorkContents != null && mWorkContents.getExamMode() == 0) {
                        CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_READ + getUserInfoBase().getUserId(), true);
                    }

                    if (mBigQuesIndex >= mResourceList.size()) {
                        return;
                    }
                    boolean isInfoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule().getInfoRetail() != 0;
                    //新的判断字段，旧的不知道有用与否

                    int infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
                    CWLog.d(TAG, "-----------lqi-----isInfoRetail: -->" + isInfoRetail + "--------------infoRetail: ------>" + infoRetail);
                    if (isInfoRetail) {
                        if (mBigQuesIndex >= mResourceList.size()) {
                            return;
                        }
                        QuestionRule listeningAndSpeakingRule = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule();
                        startReady(listeningAndSpeakingRule.getReadyTime(), false);

                    } else if (infoRetail == 2) {
                        if (mBigQuesIndex >= mResourceList.size()) {
                            return;
                        }
                        //自主提问 加入录音过程，播放子题音频资源
                        QuestionRule listeningAndSpeakingRule = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule();

                        startReady(listeningAndSpeakingRule.getReadyTime(), false);

                        lookFlag = false;
                        // 录音结束接着原来的步骤，下面的startLoadChildQuestion
                    } else {
                        if (mBigQuesIndex >= mResourceList.size()) {
                            return;
                        }
                        List<Questions> smallQuesList1 = mResourceList.get(mBigQuesIndex).getQuestions();
                        Questions smallQuestion = smallQuesList1.get(mSmallQuesIndex);
                        List<Questions> childQuesList = smallQuestion.getChildren();
                        startLoadChildQuestion(childQuesList.get(mChildQuesIndex), true, mResourceList);
                    }
                    break;
                case READY_CHILD_QUESTION:// 子题准备倒计时结束
                    Log.e("bottomview", "############子题准备倒计时结束############mReadyTime###" + mReadyTime);

                    if (mReadyTime > 0) {
                        CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_PREPARE + getUserInfoBase().getUserId(), true);

                    }

                    startAnswerQuestion();
                    break;
                case ANSWER:// 答题结束      ///答题结束   位置
                    CWLog.i(TAG, "答题/录音结束自动切换到下一题");
                    totalQuesIndex = mQuesTotalIndex + 1;
                    bigQuesIndex = mResourceList.get(mBigQuesIndex).getIndex() + 1;
                    if (mChildQuesIndex == -1) {
                        quesNo = (bigQuesIndex) + "." + (mSmallQuesIndex + 1);
                    } else {
                        quesNo = (bigQuesIndex) + "." + (mSmallQuesIndex + 1) + "." + (mChildQuesIndex + 1);
                    }
                    if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE
                            || mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
                        try {
                            CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_ANSWER + getUserInfoBase().getUserId(), true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ls_bottom_view.setStateBarVisibility(View.VISIBLE);
                        //提前结束答题不需要提示语
                        if (mAheadRecord) {
                            mAheadRecord = false;
                            autoSwitchNextQuestion(mResourceList);

                        } else {
                            status = ListenSpeakUtil.State.END_AUDIO;
                            //
                            //1、停止答题时，选择题，这个图标不应该显示在这里
                            //2、停止答题时，填空题时，键盘应该隐藏掉
                            //3、选择和填空题，播放“停止答题”的提示语时，还能做题，---应控制不能做题了
                            question_layout.enableBlankInput();
                            question_layout.allowAnswer(true);
                            ls_bottom_view.setRecordState(false, -1);
                            // 答题结束提示语
                            AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_END_ANSWER, NewListenSpeakActivity.this, null);
                        }


                    } else {
                        //录音结束   加播结束音频
                        CWSys.setSharedBoolean(EConstants.SHARE_KEY_LSW_TIPS_RECORD + getUserInfoBase().getUserId(), true);
                        ls_bottom_view.microRecordingSetVisibility(View.GONE);

                        if (mp3Recorder != null) {
                            isStopFlag = false;
                            mp3Recorder.stop();
                        }
                    }
                    break;
            }

        } catch (Exception e) {
            ToastUtil.INSTANCE.toastCenterError("答题似乎出现一点问题...");
            e.getStackTrace();
        }

    }


    /**
     * 开始答题
     */
    protected void startAnswerQuestion() {
        try {
            status = ListenSpeakUtil.State.ANSWER;

            //允许选择题开始答题
            question_layout.allowAnswer(true);

            printState();
            // 进入答题状态
            AudioPlayer.getInstance().play(mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE || mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK ? ListenSpeakUtil.SoundUrl.SOUND_START_ANSWER : ListenSpeakUtil.SoundUrl.SOUND_START_AUDIO, this, null);
        } catch (NullPointerException e) {

        }
    }


    private void onBigStemPlayOver() {

        Log.e(TAG, "onBigStemPlayOver: ");
        playCount = 0;

        if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE || mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) { // 开始看题
            if (mBigQuesIndex >= mResourceList.size()) {
                return;
            }
            // 加载选项布局
            Questions smallQuestion = mResourceList.get(mBigQuesIndex).getQuestions().get(mSmallQuesIndex);

            Log.d(TAG, "######  BIG_QUESTION_STEM loadOptionLayout ######" + status);

            question_layout.loadOptionLayout(smallQuestion.getOptions(), mQuestionType);

        }

        //题干不高亮，内容高亮
        question_layout.setBigStemHighLight(false);


        //1 信息转述 2 自主提问 3 视频朗读
        List<String> urlList = null;
        Questions questions = null;
        if (mBigQuesIndex >= mResourceList.size()) {
            return;
        }
        int infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();

        if (null != mResourceList.get(mBigQuesIndex).getQuestions() && mSmallQuesIndex < mResourceList.get(mBigQuesIndex).getQuestions().size()) {
            questions = mResourceList.get(mBigQuesIndex).getQuestions().get(mSmallQuesIndex);
            urlList = ListenSpeakUtil.getVideoPath(questions.getTrunk());
        }
        //3  视频朗读
        if (infoRetail == 3 && null != urlList && urlList.size() > 0 && !isBigQuesSwitch && !isStopFlag) {
            //视频朗读类型
            ViedoJumpManager.jumpToListenSpeakVideo(R.string.go_back, NewListenSpeakActivity.this, EpaperConstant.REQUEST_CODE_LISTEN_SPEAK_VIDEO, urlList.get(0), EpaperConstant.LISTEN_SPEAK_PLAY_TYPE_NO_NEED_RECORD, null, mResourceName, question_layout.getBigStem());
        } else {
            // 开始播放小题音频
            //是否是自主练习切换大题
            isBigQuesSwitch = false;
            //开始加载小题题干和附件
            startLoadSmallQuestion(mResourceList, questions);
        }

        //允许选择题开始答题
        question_layout.allowAnswer(true);
        if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
            question_layout.showSoftInput(false);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.TOTAL_TIMER, mHandler);
        isStopHandler = true;
        isStopFlag = true;

        switchRelease(mRecorderHandler);
        AudioPlayer.getInstance().stop();
        AudioPlayer.getInstance().release();
        if (timer != null) {
            timer.cancel();
        }
        BaseRequestUtil.getInstance().cancelAll(TAG);
    }

    /**
     * 获取听说模块试卷数据
     */
    public void getExamData() {
        getExamData(false);
    }

    /**
     * 获取听说模块试卷数据
     *
     * @param isOver 是否完成了学习
     */
    public void getExamData(final boolean isOver) {

        showMiddleProgressBar(getTitleText());

        String path;
        if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
            path = ESystem.getPackagesJsonPathNew(mDownLoadInfo.getBookId(), mDownLoadInfo.getChapterId(), mDownLoadInfo.getModuleId(), mDownLoadInfo.getVersionId());
        } else {
            path = ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());
        }

        //path = ESystem.getProjectFolderPath() + File.separator + "select3.txt";
        //获取作业资源
        EpaperDao.getInstance().getSerializableObjects(path,
                ListenspeakExam.class, new BaseExtCallBack(mActivity) {

                    @Override
                    public void success(final Object data) {
                        super.success(data);
                        mExamData = (ListenspeakExam) data;
                        List<String> errorResourceList = new ArrayList<>();
                        if (doWorkType == 1) {
                            if (mWorkContents != null && !TextUtils.isEmpty(mWorkContents.getErrorResource())) {
                                // 有错题
                                String[] errorResource = mWorkContents.getErrorResource().split(",");
                                errorResourceList = Arrays.asList(errorResource);
                            }
                        }
                        /**
                         * 选中的资源(同步跟读：id字符串；听说模考：下标字符串)//选择布置的
                         * 目前只有听说模考有字段内容，比如一份试卷有10题只选中其中几题布置
                         */
                        if (!TextUtils.isEmpty(checkedResource)) {
                            // 有选题
                            String[] checkedQuesIndexs = checkedResource.split(",");
                            List<ResourceDetail> items = new ArrayList<ResourceDetail>();
                            for (String quesIndex : checkedQuesIndexs) {
                                int bigQuesIndex = Integer.parseInt(quesIndex);
                                ResourceDetail mResourceDetail = mExamData.getItems().get(bigQuesIndex);
                                mResourceDetail.setIndex(bigQuesIndex);
                                mResourceDetail.setDo(false);
                                if (doWorkType == 1 && errorResourceList.size() > 0) {
                                    //订正错题
                                    List<Questions> errorQuestions = new ArrayList<>();
                                    for (Questions mQuestionItem : mResourceDetail.getQuestions()) {
                                        int minQuest = mQuestionItem.getChildren().size();
                                        if (minQuest == 0) {
                                            //没有子题目
                                            String versionId = mQuestionItem.getVersionId();
                                            if (errorResourceList.contains(versionId)) {
                                                errorQuestions.add(mQuestionItem);
                                            }
                                        } else {
                                            //有子题目
                                            List<Questions> children = mQuestionItem.getChildren();
                                            List<Questions> errorChildren = new ArrayList<>();
                                            for (Questions mCQuestionItem : children) {
                                                String versionId = mCQuestionItem.getVersionId();
                                                if (errorResourceList.contains(versionId)) {
                                                    errorChildren.add(mCQuestionItem);
                                                }
                                            }
                                            if (errorChildren.size() > 0) {
                                                mQuestionItem.setChildren(errorChildren);
                                                errorQuestions.add(mQuestionItem);
                                            }
                                        }
                                    }
                                    if (errorQuestions.size() > 0) {
                                        mResourceDetail.setQuestions(errorQuestions);
                                        items.add(mResourceDetail);
                                        mQuesTotal = mQuesTotal + mResourceDetail.getScores().size();
                                    }
                                } else {
                                    items.add(mResourceDetail);
                                    mQuesTotal = mQuesTotal + mResourceDetail.getScores().size();
                                }
                            }
                            if (doWorkType == 1 && errorResourceList.size() > 0) {
                                mQuesTotal = errorResourceList.size();
                                for (int i = 0; i < items.size(); i++) {
                                    ResourceDetail mResourceDetailItem = items.get(i);
                                    mResourceDetailItem.setIndex(i);
                                    mResourceDetailItem.setDo(false);
                                }
                            }
                            mExamData.setItems(items);
                        } else {
                            if (doWorkType == 1 && errorResourceList.size() > 0) {
                                //订正错题
                                List<ResourceDetail> items = new ArrayList<ResourceDetail>();
                                for (int i = 0; i < mExamData.getItems().size(); i++) {
                                    ResourceDetail mResourceDetail = mExamData.getItems().get(i);
                                    mResourceDetail.setIndex(i);
                                    mResourceDetail.setDo(false);
                                    List<Questions> errorQuestions = new ArrayList<>();
                                    for (Questions mQuestionItem : mResourceDetail.getQuestions()) {
                                        int minQuest = mQuestionItem.getChildren().size();
                                        if (minQuest == 0) {
                                            //没有子题目
                                            String versionId = mQuestionItem.getVersionId();
                                            if (errorResourceList.contains(versionId)) {
                                                errorQuestions.add(mQuestionItem);
                                            }
                                        } else {
                                            //有子题目
                                            List<Questions> children = mQuestionItem.getChildren();
                                            List<Questions> errorChildren = new ArrayList<>();
                                            for (Questions mCQuestionItem : children) {
                                                String versionId = mCQuestionItem.getVersionId();
                                                if (errorResourceList.contains(versionId)) {
                                                    errorChildren.add(mCQuestionItem);
                                                }
                                            }
                                            if (errorChildren.size() > 0) {
                                                mQuestionItem.setChildren(errorChildren);
                                                errorQuestions.add(mQuestionItem);
                                            }
                                        }
                                    }
                                    if (errorQuestions.size() > 0) {
                                        mResourceDetail.setQuestions(errorQuestions);
                                        items.add(mResourceDetail);
                                        mQuesTotal = mQuesTotal + mResourceDetail.getScores().size();
                                    }
                                }
                                if (doWorkType == 1 && errorResourceList.size() > 0) {
                                    mQuesTotal = errorResourceList.size();
                                    for (int i = 0; i < items.size(); i++) {
                                        ResourceDetail mResourceDetailItem = items.get(i);
                                        mResourceDetailItem.setIndex(i);
                                        mResourceDetailItem.setDo(false);
                                    }
                                }
                                mExamData.setItems(items);
                            } else {
                                for (int i = 0; i < mExamData.getItems().size(); i++) {
                                    ResourceDetail mResourceDetail = mExamData.getItems().get(i);
                                    mQuesTotal = mQuesTotal + mResourceDetail.getScores().size();
                                    mResourceDetail.setIndex(i);
                                    mResourceDetail.setDo(false);
                                }
                            }
                        }
                        //模式 1;// 自主练习  2;// 模拟考试
                        if (lsMode == ListenSpeakUtil.LsMode.OWN_PRACTISE || doWorkType == 1) {
                            // 获取是否做过的记录
                            SerializableManager.getInstance().deSerialize(
                                    ListenSpeakUtil.getSaveIsDoRecordKey(mDownLoadInfo, mModule, position, uuid), new BaseCallBack() {
                                        @Override
                                        public void success(Object data) {
                                            isDoRecords = (ArrayList<ResourceDetail>) data;
                                            if (isDoRecords == null
                                                    || isDoRecords.isEmpty()) {
                                                resetIsDoRecord();
                                            }
                                            hideMiddleProgressBar();
                                            loadUiOrEnd(isOver);

                                        }

                                        @Override
                                        public void failed(Object data) {
                                            resetIsDoRecord();
                                            hideMiddleProgressBar();
                                            loadUiOrEnd(isOver);
                                        }

                                        @Override
                                        public void failed(int errorCode, Object data) {
                                            failed(null);
                                        }
                                    });
                        } else {
                            hideMiddleProgressBar();
                            loadUiOrEnd(isOver);
                        }
                        boolean isUploadStartTime = CWSys.getSharedBoolean(ListenSpeakUtil.getStartDateIsUploadSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), false);
                        if (!isUploadStartTime) {
                            setDoworkProgress();
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        failed(data);
                    }

                    @Override
                    public void failed(Object data) {

                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "finish 6,获取资源失败", "听说模考追踪中途finish", true);
                        finish();
                        showToastError((int) data);
                        hideMiddleProgressBar();
                    }
                }

        );
    }


    /**
     *
     */

    public void loadUiOrEnd(final boolean isOver) {
        if (!isOver || lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {

            loadUi();

        } else {
            // 说明已做完  开始未结束

            EpaperJumpManager.jumpToListenSpeakResult(R.string.listen_speak,
                    mActivity, isCorrect, mDownLoadInfo, mModule, checkedResource, position, intentWorkId, mClassId, workTime, mServiceId, mLswAnswerList, mExamData,
                    RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, mWorkContents, lsMode, doWorkType, effectivDate);

//            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "finish 5", "听说模考追踪中途finish", true);

            finish();
        }
    }


    /**
     * 加载UI    开始
     */
    private void loadUi() {
        String tag = "";
        if (doWorkType == 1) {
            tag = "订正错题  ";
        }
        setTitleText(tag + mResourceName);

        if (mExamData != null) {
            // 自主练习
            if (lsMode == ListenSpeakUtil.LsMode.OWN_PRACTISE || doWorkType == 1) {
                setRightBtnBG(R.mipmap.nav_switch_question);
                setRightBtnListener(new ViewOnClickListener() {
                    @Override
                    public void avertRepeatOnClick(View v) {
                        // 更新时间
                        //                        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
                        //自主联系 选题 界面   回调 REQ_CODE_TO_SELECT_QUESTION
                        //resetIsDoRecord();
                        SelectQuestionDialog selectQuestionDialog = new SelectQuestionDialog(NewListenSpeakActivity.this, isDoRecords);
                        Window dialogWindow = selectQuestionDialog.getWindow();
                        //设置Dialog从窗体底部弹出
                        dialogWindow.setGravity(Gravity.BOTTOM);
                        WindowManager.LayoutParams lp = selectQuestionDialog.getWindow().getAttributes();
                        lp.width = DisplayUtils.getScreenWidth(getApplicationContext()); //设置宽度
                        selectQuestionDialog.getWindow().setAttributes(lp);
                        selectQuestionDialog.setCanceledOnTouchOutside(true);
                        selectQuestionDialog.setCancelable(true);

                        selectQuestionDialog.setOnSelectQuestionListener(new SelectQuestionDialog.OnSelectQuestionListener() {
                            @Override
                            public void onSelectQuestion(int index, boolean isCommit) {

                                if (!isCommit) {// 选择完作业回调
                                    //                                    int selectQuesIndex = data.getIntExtra(IntentFlag.INTENT_FLAG_ID, 0);
                                    if (index != mBigQuesIndex) {
                                        //重新开始某题
                                        restartBigQuestion(index);
                                    }

                                } else {
                                    // 选题页面点击提交作业按钮回调
                                    toSubmitAnswer();
                                }

                            }
                        });
                        selectQuestionDialog.show();


                    }
                });
            }

            mResourceList = mExamData.getItems();// 资源集合


            if (mResourceList != null && !mResourceList.isEmpty()) {
                // int questionSize = getAnswerCardData().size();
                int questionSize = mResourceList.size();
                bottomProgress.setPoint(questionSize);
                bottomProgress.setInit();
                bottomProgress.invalidate();
                bottomNo.setHint(getString(R.string.show_bottom_no, 1, questionSize));

                // workTime = limitTime = mExamData.getLimitTime() * 60;//
                // 将分钟转化成秒
                question_layout.setShowTotalTime(DateFormat.showTime(workTime));
                if (mBigQuesIndex >= mResourceList.size()) {
                    return;
                }
                final ResourceDetail firstResourceDetail = mResourceList.get(mBigQuesIndex);// 取大题资源

                if (firstResourceDetail != null) {

                    final ModuleSet moduleSet = firstResourceDetail.getTemplateSettings();// 大题模块设置

                    if (moduleSet != null) {


                        //是否展示过选择选题引导页
                        boolean isShowSelectQuestion = CWSys.getSharedBoolean(EConstants.SHARE_KEY_IS_SHOW_LSW_TIP_SELECT + getUserInfoBase().getUserId(), false);
                        //展示提示对话框
                        final boolean isShow = CWSys.getSharedBoolean(EConstants.SHARE_KEY_IS_SHOW_LSW_TIP + getUserInfoBase().getUserId(), false);


                        //young  new question of long  or short
                        if (moduleSet.getIsPartView() == 1) {//short

                        } else if (moduleSet.getInfoRetail() == 11) {
                            //long

                        } else {
                            showRecordTips();
                            //考试开始预先加载大题和选项
                            if (mBigQuesIndex >= mResourceList.size()) {
                                return;
                            }
                            int questionType = question_layout.initBigQuestionAndOptions(mResourceList, mBigQuesIndex, mSmallQuesIndex, ls_bottom_view.getSeekBarView());
                            if (questionType > 0) {
                                mQuestionType = questionType;
                            }
                        }


                        if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {

                            ArrayList<LswAnswer> lswAnswers = new ArrayList<LswAnswer>();
                            try {
                                List<Questions> childQuesList = null;
                                if (mRetryIndex < mResourceList.size()) {
                                    ResourceDetail resourceDetail = mResourceList.get(mRetryIndex);
                                    List<Questions> smallQuesList = resourceDetail.getQuestions();
                                    for (Questions question : smallQuesList
                                            ) {
                                        childQuesList = question.getChildren();
                                        if (childQuesList != null && !childQuesList.isEmpty()
                                                && childQuesList.size() > 0) {
                                            for (Questions childquestion : childQuesList
                                                    ) {
                                                for (LswAnswer l : ReDolswAnswerArrayList
                                                        ) {
                                                    if (l.getVersionId().equals(childquestion.getVersionId())) {
                                                        lswAnswers.add(l);
                                                    }
                                                }

                                            }

                                        } else {
                                            for (LswAnswer l : ReDolswAnswerArrayList) {
                                                if (l.getVersionId().equals(question.getVersionId())) {
                                                    lswAnswers.add(l);
                                                }
                                            }
                                        }

                                    }
                                }
                            } catch (Exception e) {
                                e.getStackTrace();
                            }

                            //young  new question of long  or short

                            if (moduleSet.getIsPartView() == 1) {//short
                                EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(1, R.string.go_back, NewListenSpeakActivity.this,
                                        isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                                        false, lswAnswers, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);

                            } else if (moduleSet.getInfoRetail() == 11) {
                                //long
                                EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(11, R.string.go_back, NewListenSpeakActivity.this,
                                        isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                                        false, lswAnswers, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);
                            } else {
                                startTotalCount();
                                startLoadBigQuestion(mResourceList);
                            }


                        } else if ((lsMode == ListenSpeakUtil.LsMode.OWN_PRACTISE || doWorkType == 1) && !isShowSelectQuestion) { //第一次自主练习进来
                            CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_SHOW_LSW_TIP_SELECT + getUserInfoBase().getUserId(), true);

                            final LswSelectTipDialog lswSelectTipDialog = new LswSelectTipDialog(NewListenSpeakActivity.this);
                            lswSelectTipDialog.setOnKnowListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    lswSelectTipDialog.dismiss();

                                    //可能之前从作业列表进入过
                                    if (!isShow) {
                                        CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_SHOW_LSW_TIP + getUserInfoBase().getUserId(), true);
                                        final LswTipDialog lswTipDialog = new LswTipDialog(NewListenSpeakActivity.this);
                                        lswTipDialog.setStemText(moduleSet.getContent());
                                        lswTipDialog.setSettingListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                lswTipDialog.dismiss();
                                                MeJumpManager.jumpToMainActivity(mActivity, R.string.go_back,
                                                        EpaperConstant.REQUEST_CODE_LSW_JUMP_SETTING, MainActivity.JUMP_SORECE_TYPE_LSW);
                                                //
                                                //


                                            }
                                        });

                                        lswTipDialog.setNotSettingListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                lswTipDialog.dismiss();
                                                //young  new question of long  or short
                                                if (moduleSet.getIsPartView() == 1) {//short
                                                    //总计时开始
                                                    startTotalCount();
                                                    EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(1, R.string.go_back, NewListenSpeakActivity.this,
                                                            isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                                                            true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);


                                                } else if (moduleSet.getInfoRetail() == 11) {
                                                    //总计时开始
                                                    startTotalCount();
                                                    //long
                                                    EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(11, R.string.go_back, NewListenSpeakActivity.this,
                                                            isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                                                            true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);

                                                } else {
                                                    //播放 开始考试音频
                                                    AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_START_EXAM, mActivity, null);
                                                }

                                            }
                                        });
                                        lswTipDialog.show();

                                    } else {

                                        //young  new question of long  or short
                                        if (moduleSet.getIsPartView() == 1) {//short
                                            //总计时开始
                                            EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(1, R.string.go_back, NewListenSpeakActivity.this,
                                                    isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                                                    true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);


                                        } else if (moduleSet.getInfoRetail() == 11) {
                                            //long
                                            //总计时开始
                                            startTotalCount();
                                            EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(11, R.string.go_back, NewListenSpeakActivity.this,
                                                    isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                                                    true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);

                                        } else {
                                            //播放 开始考试音频
                                            AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_START_EXAM, mActivity, null);
                                        }
                                    }

                                }
                            });

                            lswSelectTipDialog.show();
                        } else if (!isShow) {//第一次作业列表进来
                            CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_SHOW_LSW_TIP + getUserInfoBase().getUserId(), true);
                            final LswTipDialog lswTipDialog = new LswTipDialog(NewListenSpeakActivity.this);
                            lswTipDialog.setStemText(moduleSet.getContent());
                            lswTipDialog.setSettingListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    lswTipDialog.dismiss();

                                    MeJumpManager.jumpToMainActivity(mActivity, R.string.go_back,
                                            EpaperConstant.REQUEST_CODE_LSW_JUMP_SETTING, MainActivity.JUMP_SORECE_TYPE_LSW);

                                    //                                    MeJumpManager.jumpToReadSetting(mActivity, R.string.go_back,
                                    //                                            EpaperConstant.REQUEST_CODE_LSW_JUMP_SETTING);
                                }
                            });

                            lswTipDialog.setNotSettingListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    lswTipDialog.dismiss();
                                    //young  new question of long  or short
                                    if (moduleSet.getIsPartView() == 1) {//short
                                        //总计时开始
                                        startTotalCount();
                                        EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(1, R.string.go_back, NewListenSpeakActivity.this,
                                                isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid, true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);
                                    } else if (moduleSet.getInfoRetail() == 11) {
                                        //总计时开始
                                        startTotalCount();
                                        //long
                                        EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(11, R.string.go_back, NewListenSpeakActivity.this,
                                                isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid, true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);


                                    } else {
                                        //播放 开始考试音频
                                        AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_START_EXAM, mActivity, null);
                                    }

                                }
                            });
                            lswTipDialog.show();
                        } else {

                            //young  new question of long  or short
                            if (moduleSet.getIsPartView() == 1) {//short
                                //总计时开始
                                startTotalCount();
                                EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(1, R.string.go_back, NewListenSpeakActivity.this,
                                        isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid, true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);
                            } else if (moduleSet.getInfoRetail() == 11) {
                                //总计时开始
                                startTotalCount();
                                //总计时开始
                                EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(11, R.string.go_back, NewListenSpeakActivity.this,
                                        isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                                        true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);
                            } else {
                                //播放 开始考试音频
                                AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_START_EXAM, mActivity, null);
                            }
                        }


                    }
                }
            }
        }
    }


    /**
     * 开始录制
     */
    private void startRecorder() {
        //音频保存地址
        mRecorderPath = ESystem.getAnswersMediaPath(uuid) + File.separator + System.currentTimeMillis() + EConstants.AUDIO_DEFAULT_SUFFIX;
        CWSys.setSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), uuid);


        CWLog.d(TAG, "开始录音");

        mp3Recorder = new Mp3Recorder(mRecorderPath, BaseConstants.SAMPLERATE, mRecorderHandler);

        //        mp3Recorder = new Mp3Recorder(mRecorderPath, BaseConstants.SAMPLERATE);


        mp3Recorder.setOnRecorderListener(new OnRecorderListener() {
            @Override
            public void onRecorderListener(int msgType) {

                CWLog.d(TAG, "######onRecorderListener msgType#########" + msgType);
            }
        });

        mp3Recorder.start();
    }


    /**
     * 重置是否做的记录
     */
    protected void resetIsDoRecord() {
        isDoRecords = new ArrayList<>();
        if (mExamData != null) {
            for (ResourceDetail rd : mExamData.getItems()) {
                isDoRecords.add(rd);
            }
        }

    }


    /**
     * 去提交答案  点击提交作业  和结束提交答案
     */
    private void toSubmitAnswer() {
        ls_bottom_view.hideTimerAnimation();

        //        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.TOTAL_TIMER, mHandler);

        isStopHandler = true;
        isStopFlag = true;
        switchRelease(mRecorderHandler);
        AudioPlayer.getInstance().stop();
        AudioPlayer.getInstance().release();
        //可到另外一个页面判断是否评分完成
        {// 评分结束
            userAnswerOver();
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK) {
                setResult(RESULT_OK);

                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "finish 7", "听说模考追踪中途finish", true);
                finish();
            } else if (requestCode == REQ_CODE_TO_SELECT_QUESTION) { //去选题界面

                if (data != null) {// 选择完作业回调
                    int selectQuesIndex = data.getIntExtra(IntentFlag.INTENT_FLAG_ID, 0);
                    if (selectQuesIndex != mBigQuesIndex) {
                        restartBigQuestion(selectQuesIndex);
                    }
                } else {
                    // 选题页面点击提交作业按钮回调
                    toSubmitAnswer();
                }


            } else if (requestCode == EpaperConstant.REQUEST_CODE_LISTEN_SPEAK_VIDEO) {

                if (data != null) {

                    int phoneState = data.getIntExtra(IntentFlag.INTENT_FLAG_HONE_STATUS, -1);
                    if (phoneState == TelephonyManager.CALL_STATE_RINGING || phoneState == IntentValue.STATE_EXIT_BY_USER) {
                        finish();
                    }

                }
                //大题题干播放视频后回来
                if (mBigQuesIndex >= mResourceList.size()) {
                    return;
                }
                int infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
                Questions questions = mResourceList.get(mBigQuesIndex).getQuestions().get(mSmallQuesIndex);
                if (infoRetail == 3) {
                    //视频朗读类型，自主提问类型，小题加入视频播放
                    // 开始播放小题音频
                    startLoadSmallQuestion(mResourceList, questions);
                }

            } else if (requestCode == EpaperConstant.REQUEST_CODE_LISTEN_SPEAK_VIDEO_AND_RECORD) {
                //                if (!recordFail)

                if (data != null) {
                    int phoneState = data.getIntExtra(IntentFlag.INTENT_FLAG_HONE_STATUS, -1);
                    if (phoneState == TelephonyManager.CALL_STATE_RINGING || phoneState == IntentValue.STATE_EXIT_BY_USER) {
                        finish();
                    }

                }

                //边录边播
                CWSys.setSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), uuid);
                status = ListenSpeakUtil.State.END_AUDIO;
                AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_END_AUDIO, NewListenSpeakActivity.this, null);

            } else if (requestCode == EpaperConstant.REQUEST_CODE_LISTEN_SPEAK_INDEPENDENT_QUESTION) {
                if (mBigQuesIndex >= mResourceList.size()) {
                    return;
                }

                int infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
                List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
                Questions smallQuestion = smallQuesList.get(mSmallQuesIndex);

                if (infoRetail == 2) {
                    //自主提问类型
                    // 开始播放小题音频
                    startLoadSmallQuestion(mResourceList, smallQuestion, true);
                }

            } else if (requestCode == REQUEST_CODE_FOR_LONG_OR_SHORT) {   //长短对话回来
                if (data != null) {
                    int phoneState = data.getIntExtra(IntentFlag.INTENT_FLAG_HONE_STATUS, -1);
                    if (phoneState == TelephonyManager.CALL_STATE_RINGING || phoneState == IntentValue.STATE_EXIT_BY_USER) {
                        finish();
                    }
                    AudioPlayer.getInstance().setOnPlayListener(playListener);

                    List<LswAnswer> returnLswAnswerList = (List<LswAnswer>) data.getSerializableExtra(IntentFlag.INTENT_FLAG_LISTEN_SPEAK_ANSWERS);
                    int returnNextBigIndex = data.getIntExtra(IntentFlag.INTENT_FLAG_LISTEN_SPEAK_NEXT_BIGINDEX, 0);
                    int returnTotalIndex = data.getIntExtra(IntentFlag.INTENT_FLAG_LISTEN_SPEAK_TOTAL_INDEX, totalQuesIndex);
                    boolean isFromBackButton = data.getBooleanExtra(IntentFlag.INTENT_FLAG_FROM_BACK_BUTTON, false);
                    boolean isFromCompleteButton = data.getBooleanExtra(IntentFlag.INTENT_FLAG_FROM_COMPLETED_BUTTON, false);
                    boolean isFromCompelteQuestion = data.getBooleanExtra(IntentFlag.INTENT_FLAG_FROM_COMPLETED_QUESTION, false);
                    //如果返回答案不为空就保存
                    if (returnLswAnswerList != null && returnLswAnswerList.size() > 0) {
                        for (LswAnswer lswAnswer : returnLswAnswerList) {
                            addAnswerToAnswerList(lswAnswer);
                        }
                        //缓存答案到本地
                        serializeRecord(mBigQuesIndex, workTime, mQuesTotalIndex, mSmallQuesIndex, status);
                    }


                    //作业模式，自主学习模式，按返回键时处理
                    if (isFromBackButton) {
                        finish();
                        return;
                    }

                    //如果是重做模式，直接把结果返回给重做页面
                    if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {
                        LsRedoAnswersEvent lsRedoAnswersEvent = new LsRedoAnswersEvent();
                        lsRedoAnswersEvent.setIsDoRecords(isDoRecords);
                        lsRedoAnswersEvent.setLswAnswers(mLswAnswerList);
                        lsRedoAnswersEvent.setWorkTime(workTime);
                        EventBus.getDefault().post(lsRedoAnswersEvent);
                        finish();
                        return;
                    } else if (lsMode == ListenSpeakUtil.LsMode.HOME_WORK_MODE) {
                        mBigQuesIndex = returnNextBigIndex;
                        mQuesTotalIndex = returnTotalIndex;
                        if (mBigQuesIndex >= mResourceList.size()) {
							/*status = ListenSpeakUtil.State.END;
							AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_END_EXAM, this, null);*/
                            listenspEnd();

                        } else {
                            serializeBigQuesIndex(true, mBigQuesIndex);
                            restartBigQuestion(mBigQuesIndex);
                        }
                    } else {    //自主学习模式
                        //如果是流程走完返回，表示该题做完
                        if (isFromCompelteQuestion) {
                            //作业列表进来size可能为0
                            if (isDoRecords != null && isDoRecords.size() > 0) {
                                // 当前大题已做完，准备切换到下一大题
                                if (mBigQuesIndex < isDoRecords.size()) {
                                    //自主学习
                                    // 当前大题已做完，准备切换到下一大题
                                    ResourceDetail demoo = new ResourceDetail();
                                    demoo.setIndex(mBigQuesIndex);
                                    int index = isDoRecords.indexOf(demoo);
                                    if (isDoRecords.size() > index && index >= 0) {
                                        isDoRecords.get(index).setDo(true);
                                    } else {
                                        isDoRecords.get(mBigQuesIndex).setDo(true);
                                    }
                                }
                                if (iRefreshDoRecord != null) {// 刷新选题界面
                                    iRefreshDoRecord.refreshDoRecord(isDoRecords);
                                }
                                SerializableManager.getInstance().serialize(ListenSpeakUtil.getSaveIsDoRecordKey(mDownLoadInfo, mModule, position, uuid), isDoRecords);// 保存是否做的记录
                            }
                        }


                        //直接到提交页
                        if (isFromCompleteButton) {
                            listenspEnd();
                        } else {
                            mBigQuesIndex = returnNextBigIndex;
                            mQuesTotalIndex = returnTotalIndex;
                            //是否做完了所有题
                            if (mBigQuesIndex >= mResourceList.size()) {
                                listenspEnd();
                            } else {
                                if (isDoRecords != null && isDoRecords.size() > 0) {
                                    //判断接下来的大题是否已经是做完的，做完就跳到下一题
                                    for (; mBigQuesIndex < isDoRecords.size(); mBigQuesIndex++) {
                                        boolean isDo = isDoRecords.get(mBigQuesIndex).isDo();
                                        if (!isDo) {// 还没做
                                            serializeBigQuesIndex(true, mBigQuesIndex);
                                            restartBigQuestion(mBigQuesIndex);
                                            break;
                                        } else {// 已经做过了
                                            mQuesTotalIndex++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (resultCode == RESULT_CANCELED) {
            //如果是重做模式，按返回键是不保存记录的，也需要关闭该主流程Activity
            if (requestCode == REQUEST_CODE_FOR_LONG_OR_SHORT) {
                finish();
            }
        }


        if (requestCode == EpaperConstant.REQUEST_CODE_LSW_JUMP_SETTING) {

            isReadBigQuestionStem = CWSys.getSharedBoolean(EConstants.SHARE_KEY_IS_PLAY_STEM_AUDIO + getUserInfoBase().getUserId(), true);
            final ModuleSet moduleSet = mResourceList.get(mBigQuesIndex).getTemplateSettings();// 大题模块设置
            if (moduleSet.getIsPartView() == 1) {//short
                EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(1, R.string.go_back, NewListenSpeakActivity.this,
                        isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                        true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);
            } else if (moduleSet.getInfoRetail() == 11) {
                EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(11, R.string.go_back, NewListenSpeakActivity.this,
                        isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid,
                        true, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);
            } else {
                //播放 开始考试音频
                AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_START_EXAM, this, null);
            }

        }
    }


    private Questions getCurentEvaluateQuestions() {
        Questions curQuestions = null;
        try {

            if (mBigQuesIndex < mResourceList.size()) {
                List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex)
                        .getQuestions();
                if (smallQuesList != null && !smallQuesList.isEmpty()) {
                    Questions smallQues = smallQuesList.get(mSmallQuesIndex);
                    List<Questions> childQuesList = smallQues.getChildren();
                    curQuestions = smallQues;
                    if (childQuesList != null && !childQuesList.isEmpty()) {
                        Questions childQues = childQuesList.get(mChildQuesIndex);
                        curQuestions = childQues;
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }


        return curQuestions;
    }


    public void listenspEnd() {
        mBigQuesIndex = mExamData.getItems().size();
        serializeRecord(mBigQuesIndex, workTime, mQuesTotalIndex, mSmallQuesIndex, status);
        toSubmitAnswer();
    }

    //获取用户当前答案和题目
    private LswAnswer getCurrentLswAnswer() {
        LswAnswer lswAnswer = new LswAnswer();
        try {
            //当前要评测的小题
            Questions mCurrentQues = getCurentEvaluateQuestions();

            //获取参考分数列表
            List<QuestionScore> smallQuesScores = mResourceList.get(mBigQuesIndex)
                    .getScores();
            //获取当前评测文本
            String answerBody = ListenSpeakUtil.getAnswerBody(mCurrentQues);
            boolean isAnswerBody = !TextUtils.isEmpty(answerBody);
            String body = isAnswerBody ? answerBody
                    : mCurrentQues.getTrunk().getBody();
            if (TextUtils.isEmpty(body)) body = " ";

            //取出参考分值
            for (QuestionScore q : smallQuesScores
                    ) {
                //分数的versionID可以匹配题目的VERSIONid
                if (mCurrentQues.getVersionId().equals(q.getQuestionVersionId())) {
                    lswAnswer.setRefScore(q.getScore());
                }
            }
            lswAnswer.setQtype(mCurrentQues.getType());
            lswAnswer.setIs_objective(mCurrentQues.getIs_objective());
            lswAnswer.setWorkSaveUUid(uuid);
            lswAnswer.setVersionId(mCurrentQues.getVersionId());
            if (isCorrect && null != mWorkContents) {
                lswAnswer.setDoWorkId(mWorkContents.getDoWorkId());
            }

            lswAnswer.setUploadState(LswAnswer.FAIL);

            lswAnswer.setBigQuesIndex(bigQuesIndex);
            lswAnswer.setQuesNo(quesNo);
            lswAnswer.setTotalQuesIndex(totalQuesIndex);


            lswAnswer.setAnswerType(Questions.AnswerType.QUESTION_TYPE_VOICE);

            List<AnswerContent> answerContents = new ArrayList<AnswerContent>();
            AnswerContent answerContent = new AnswerContent();
            Log.d(TAG, "#######评测文本 body#########" + body);
            answerContent.setRefAnswer(body);
            answerContent.setContent(mRecorderPath);
            answerContent.setSid(0);
            //            answerContent.setAnswerType(mCurrentQues.getType());
            answerContents.add(answerContent);
            lswAnswer.setAnswerContents(answerContents);

        } catch (Exception e) {
            e.getStackTrace();
        }
        return lswAnswer;
    }


    private void restartBigQuestion(int restartIndex) {

        ls_bottom_view.setPlayBtnState(false);

        question_layout.optionsLayoutRemoveAllViews();

        question_layout.imgContainerSetVisibility(View.GONE);
        isBigQuesSwitch = true;


        switchRelease(mRecorderHandler);

        question_layout.setSmallQuestionStem(null);

        question_layout.setChildQuestionStem(null, isNewVersion);
        mBigQuesIndex = restartIndex;
        mSmallQuesIndex = 0;

        switchBigQuestion(mResourceList);

        startLoadBigQuestion(mResourceList);

    }


}
